package com.hrt.datasender.datadao.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.btcode.db.executer.IDataExecuter;
import com.btcode.orm.executer.IORMExecuter;
import com.hrt.datasender.datadao.model.BdSourceModel;
import com.hrt.datasender.datadao.model.BdSourceSingleModel;
import com.hrt.db.DBManager;

public final class BdSourceSingleService {

    private static volatile BdSourceSingleService instance;

    private BdSourceSingleService() {

    }

    public static BdSourceSingleService getInstance() {
        if (instance == null) {
            synchronized (BdSourceSingleService.class) {
                if (instance == null) {
                    instance = new BdSourceSingleService();
                }
            }
        }
        return instance;
    }

    public void clearRecord() {

        IDataExecuter dataExecuter = DBManager.getDataExecuter();
        String sql = " DELETE FROM BD_SOURCE_SINGLE ";

        dataExecuter.delete(sql, null);
    }

    /**
     * 获取最后一条实时数据
     * @return
     */
    public List<BdSourceModel> getLastSourceData() {
        IORMExecuter ormExecuter = DBManager.getORMExecuter();
        String datasql = " SELECT * FROM BD_SOURCE_SINGLE ";
        List<BdSourceModel> models = ormExecuter.getModelListSQL(datasql, null, BdSourceModel.class);

        for (BdSourceModel model : models) {
            model.setDatatime(models.get(0).getDatatime());
            // 重新设置DataId
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            model.setDataId(model.getParamCodeBus() + df.format(new Date()));
        }

        return models;
    }

    public void update(List<BdSourceModel> models) {

        IORMExecuter ormExecuter = DBManager.getORMExecuter();

        for (BdSourceModel sourceModel : models) {
            BdSourceSingleModel singleModel = new BdSourceSingleModel();

            singleModel.setCreatetime(new Date());
            singleModel.setDatatime(sourceModel.getDatatime());
            singleModel.setMeasAvg(sourceModel.getMeasAvg());
            singleModel.setMeasMax(sourceModel.getMeasMax());
            singleModel.setMeasMin(sourceModel.getMeasMin());
            singleModel.setMeasRe(sourceModel.getMeasRe());
            singleModel.setMeasZs(sourceModel.getMeasZs());
            singleModel.setParamCodeBus(sourceModel.getParamCodeBus());
            singleModel.setDataId(sourceModel.getDataId());

            BdSourceSingleModel checkModel = ormExecuter.getModel(singleModel);

            if (checkModel == null) {
                ormExecuter.create(singleModel);
            }
            else {
                ormExecuter.update(singleModel);
            }
        }
    }
}